package com.roocon.thread.ExceptionHandler;

public class ExitCapture {
  public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread(()->{
      System.out.println("The application will be exit.");
      notifyAndRelease();
    }));
    int i = 0 ;
    while (true) {
      try {
        Thread.sleep(1_000L);
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
          @Override
          public void uncaughtException(Thread thread, Throwable throwable) {
            System.out.println("uncaughtException msg:" + throwable.getMessage());
          }
        });
        System.out.println("I am working ...");
      } catch (InterruptedException e) {
          //ignoreTest2ReentrantLock
      }
      i++;
      // simulate a exception
      if (i>10) throw new RuntimeException("error");
    }
  }
  // 1. try to capture the simulate exception and handler that
  // 2. even this Thread kill by some reason can capture
  // 3. but kill -9 pid (force kill ) can't not capture
  private static void notifyAndRelease() {
    System.out.println("notify to the admin(the monitor.) by email or mq or some other way");
    try {
      Thread.sleep(1_000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Will release resource(socket,file,connection.)");

    try{
      Thread.sleep(1_000);
    }catch (Exception e){
      //ignore
    }
    System.out.println("Relase and notify Done. ");
  }
}
